package cn.darkhorse.mesadmin.task;

import cn.darkhorse.alarm.dto.AlarmParameterAndDeviceTable;
import cn.darkhorse.alarm.mapper.MesAlarmMapper;
import cn.darkhorse.alarm.pojo.AlarmParameterSettings;
import cn.darkhorse.alarm.service.AlarmHandlerService;
import cn.darkhorse.alarm.service.AlarmParameterSettingsService;
import cn.darkhorse.alarm.service.AlarmRecordInfoService;
import cn.darkhorse.alarm.service.AlarmRecordUserInfoService;
import cn.darkhorse.alarm.service.alarm.AlarmManager;
import cn.darkhorse.common.config.TaskConfig;
import cn.darkhorse.device.service.MesDeviceService;
import cn.darkhorse.jpush.service.JPushService;
import cn.darkhorse.meswechat.service.IWeChatService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
* @Description: 设备产生告警任务
* @Param:
* @return:
* @Author: Mr.Wang
* @Date:
*/
@Component("mesGenerationAlarmTask")
public class MesGenerationAlarmTask {
    @Resource
    private AlarmParameterSettingsService parameterSettingsService;
    @Resource
    private MesAlarmMapper mesAlarmMapper;
    @Resource
    protected AlarmManager alarmManager;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    private static Logger logger = LoggerFactory.getLogger(MesGenerationAlarmTask.class);
    /**
     * 产生告警
     */
//    @Scheduled(cron = "0/30 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void generation(){
        if(!TaskConfig.isFlag()){
            return;
        }
        logger.info("开始产生告警");
        long beginTime = System.currentTimeMillis();
        //false不执行定时任务
        //所有设备表
        Set<String> dataDeviceIdSet = new HashSet<>();
        //设备参数设置信息
        List<AlarmParameterAndDeviceTable> settingsList = mesAlarmMapper.getAlarmParameterAndDeviceTable();

        Map<String,List<AlarmParameterSettings>> settingsListMap = new HashMap<>(settingsList.size());
        settingsList.forEach(item -> {
            if(null != item.getHistoryTableName()){
                dataDeviceIdSet.add(item.getHistoryTableName());
                List<AlarmParameterSettings> alarmParameterSettings = settingsListMap.get(item.getHistoryTableName());
                if(null == alarmParameterSettings){
                    alarmParameterSettings = new ArrayList<>();
                    settingsListMap.put(item.getHistoryTableName(),alarmParameterSettings);
                }
                alarmParameterSettings.add(item);
            }
        });

        if(dataDeviceIdSet.isEmpty()){
            return;
        }

        for(String item:dataDeviceIdSet){
            //获取已处理的最大值
            Boolean lastDevice = stringRedisTemplate.opsForHash().hasKey("last_device", item);
            Object last_device = 0L;
            if (lastDevice){
                last_device = stringRedisTemplate.opsForHash().get("last_device", item);
            }
            if(null == last_device){
                last_device = 0L;
            }
            List<AlarmParameterSettings> parameterSettingsList = settingsListMap.get(item);
            Map<String, Object> xiongkongDevice = null;
            try {
                xiongkongDevice = mesAlarmMapper.getLastXiongkongDevice(item,Long.valueOf(last_device.toString()));
            } catch (Exception e) {
                logger.info(String.format("表【%s】不存在！",item));
                continue;
            }
            if(null == xiongkongDevice){
                logger.info(String.format("数据表【%s】未产生新告警",item));
                continue;
            }else {
                logger.info(String.format("数据表【%s】产生新告警",item));
            }
            Long id = Long.valueOf(xiongkongDevice.get("id").toString()) ;

            for(AlarmParameterSettings ps:parameterSettingsList){
                // 保存预警信息
                alarmManager.doAlarm(ps, xiongkongDevice);
            }
            //缓存最大值
            stringRedisTemplate.opsForHash().put("last_device",item,id.toString());
        }

        long endTime = System.currentTimeMillis();
        logger.info("结束产生告警");
        logger.info(String.format("此次用时%s",(endTime-beginTime)/1000));
    }







}
